package com.fly.dbexample.dao;

import android.database.Cursor;

import com.fly.db.dao.BaseDao;
import com.fly.db.util.TableUtil;
import com.fly.dbexample.FLYApplication;
import com.fly.dbexample.bean.User;

import java.util.ArrayList;

/**
 * Created with Android Studio.
 * Package_Name：com.fly.dbexample.dao
 * Project_Name：DBExample
 * User：郭鹏飞
 * Date：2016/1/19
 * Email：love518420@foxmail.com
 * Description：
 */
public class UserDao extends BaseDao {

    public UserDao(String table) {
        super(table);
    }

    public void save(User user) {
        TableUtil.invokeInsertSql(FLYApplication.getInstance().getFlySQLiteOpenHelper(),
                "user", null, new Object[]{user.getName(), user.getAge()});
    }

    public ArrayList<User> read() {
        Cursor cursor = TableUtil.invokeSelectSql(FLYApplication.getInstance().getFlySQLiteOpenHelper(),
                "user", null, null, null);
        if (cursor == null) {
            return null;
        }
        ArrayList<User> users = new ArrayList<>();
        User user;
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex("name"));
            int age = cursor.getInt(cursor.getColumnIndex("age"));
            user = new User();
            user.setName(name);
            user.setAge(age);
            users.add(user);
        }
        cursor.close();
        FLYApplication.getInstance().getFlySQLiteOpenHelper().closeDatabase();
        return users;
    }

    public void delete() {
        TableUtil.invokeDeleteSql(FLYApplication.getInstance().getFlySQLiteOpenHelper(),
                "user", null, null);
    }

}
